package com.systemCapacity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemCapacity.entity.User;
import com.systemCapacity.mapper.UserMapper;
import com.systemCapacity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<User> getUserPage(int page, int size) {
        Page<User> userPage = new Page<>(page, size);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.orderByAsc(User::getId);
        return userMapper.selectPage(userPage, userLambdaQueryWrapper);
    }

    @Override
    public boolean userExist(long userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        return getOne(wrapper) != null;
    }

    @Override
    public boolean userNameExist(String userName) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userName", userName);
        return getOne(wrapper) != null;
    }

    @Override
    public IPage<User> getUserPage(HttpServletRequest request) {
        int page;
        int size;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap.containsKey("page")) {
            page = Integer.parseInt(parameterMap.get("page")[0]);
        } else {
            page = 0;
        }
        if (parameterMap.containsKey("size")) {
            size = Integer.parseInt(parameterMap.get("size")[0]);
        } else {
            size = 20;
        }
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            if (entry.getKey().equals("page") | entry.getKey().equals("size")) {
                continue;
            }
            queryWrapper.like(entry.getKey(), entry.getValue()[0]);
        }
        Page<User> userPage = new Page<>(page, size);
        return userMapper.selectPage(userPage, queryWrapper);
    }
}
